package com.unionftech.common.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import kotlin.system.exitProcess


class ActivityCollector {
    companion object {
        private val activitys = mutableListOf<Activity>()

        @JvmStatic
        fun addActivity(activity: Activity) {
            activitys.add(activity)
        }

        @JvmStatic
        fun removeActivity(activity: Activity) {
            activitys.remove(activity)
        }

        @JvmStatic
        fun getCurrentActivity(): Activity? {
            return activitys.getOrNull(activitys.size - 1)
        }

        @JvmStatic
        fun finishAll() {
            val iterator = activitys.iterator()
            while (iterator.hasNext()) {
                val activity = iterator.next()
                if (!activity.isFinishing) {
                    activity.finish()
                    iterator.remove()
                }
            }
        }

        @JvmStatic
        fun finishActivity(cls: Class<*>) {
            for (activity in activitys) {
                if (activity.javaClass == cls) {
                    activity.finish()
                    activitys.remove(activity)
                    break
                }
            }
        }

        @JvmStatic
        fun restartApp(context: Context, mainActivityClass: Class<*>) {
            // 创建明确的启动Intent
            val intent = Intent(context, mainActivityClass).apply {
                addFlags(
                    Intent.FLAG_ACTIVITY_NEW_TASK or
                            Intent.FLAG_ACTIVITY_CLEAR_TASK or
                            Intent.FLAG_ACTIVITY_CLEAR_TOP
                )
                // 添加额外标志确保在后台也能启动（Android 10+可能需要）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    addFlags(
                        Intent.FLAG_ACTIVITY_NEW_DOCUMENT or
                                Intent.FLAG_ACTIVITY_MULTIPLE_TASK
                    )
                }
            }
            context.startActivity(intent)
            // 结束当前进程
            (context as? Activity)?.finishAffinity()
            finishAll()
            android.os.Process.killProcess(android.os.Process.myPid());
            exitProcess(0)
        }
    }
}